import axios from 'axios';
import baseDomain from './config.js';
import { notification } from 'antd';
import API from "@common/api.js";

axios.defaults.withCredentials = true;
const instance = axios.create({
  xsrfCookieName: 'xsrf-name',
  baseURL: baseDomain,
  withCredentials: true,
  xhrFields: {
    withCredentials: true
  },
  headers: { 'X-Requested-With': 'XMLHttpRequest' },
  crossDomain: true,
});
instance.interceptors.response.use(function (response) {
  console.log("response is here:");
  console.log(response);
  console.log("??????????????????")
  console.log(response.data.code == 200);
  if (response.data.code == 200) {
    return Promise.resolve(response.data)
  } else {
    notification['error']({
      message: response.data.msg
    });
    return Promise.reject({
      message: response.data.msg
    })
  }
}, function (error) {
  try {
    notification['error']({
      message: error.response.data.msg || '系统异常'
    })
    console.log(error.response.status)
    if (error.response.status === 401) {
      setTimeout(async () => {
        await API.logout();
        window.location.href = '/login';
      }, 2000);
    }
  } catch (e) {
    notification['error']({
      message: '系统异常, 请稍后再试！'
    })
  }
  return Promise.reject({
    messageCode: 'sysError'
  })
})

export default instance;